package dao;

import java.util.List;

import javax.persistence.Query;

import model.Book;
import model.Client;
import model.Order;
import model.OrderItem;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

public class OrderDao extends AbstractDao<Order> {
	
	public static Logger log =Logger.getLogger(ClientDao.class);
	private Order order;

	public Order getOrder() {
		return order;
	}
	
	/**retourne l'historique des commandes*/
	@SuppressWarnings("unchecked")
	public List<Order> getOrders(Client aUser){
		Query query = getEm().createQuery("from Order o inner join fetch o.items where o.client = :client order by o.date desc");
		query.setParameter("client", aUser);
		List<Order> result = query.getResultList();
		return result;
	}

	@Transactional
	public void setOrder(Order order) {
		this.order = order;
		em.persist(order);
	}
	
	@Transactional
	public void  addItem(Book aBook, int aQuantity){
		OrderItem item=new OrderItem();
		item.setBook(aBook);
		item.setOrder(getOrder());
		item.setQuantity(aQuantity);
		order.addItem(item);
		em.persist(item);		
	}
	
	@Transactional
	public void save(){
		em.merge(order);
	}
}
